package com.room.rest;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cyh.dao.SysConstant;
import com.room.core.annotation.LoginUser;
import com.room.core.dto.UserInfo;
import com.room.core.util.R;
import com.room.core.util.StringUtil;
import com.cyh.dao.entity.SysUser;
import com.room.core.util.UserTokenManage;
import com.room.dto.WxLoginInfo;
import com.room.dto.WxSubscribeDto;
import com.room.service.SysUserService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wx/auth")
public class WxAuthController {

    @Autowired
    private WxMaService wxService;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 微信登录
     *
     * @param wxLoginInfo
     * @param request
     * @return
     */
    @PostMapping("login_by_weixin")
    public R loginByWeixin(@RequestBody WxLoginInfo wxLoginInfo, HttpServletRequest request) throws WxErrorException {

        String sessionKey = null;
        String openId = null;
        try {
            WxMaJscode2SessionResult result = this.wxService.getUserService().
                    getSessionInfo(wxLoginInfo.getCode());
            sessionKey = result.getSessionKey();//会话密钥
            openId = result.getOpenid(); //用户唯一标识
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (StringUtil.isEmpty(sessionKey) || StringUtil.isEmpty(openId)) {
            return R.fail();
        }

        SysUser user = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().
                eq(SysUser::getWeixinOpenid, openId));
        if (user == null) {
            user = new SysUser();
            user.setUsername(openId);
            user.setPassword(openId);
            user.setWeixinOpenid(openId);
            user.setLearnLen(0);
            user.setAvatarUrl(wxLoginInfo.getUserInfo().getAvatarUrl());
            user.setNickName(wxLoginInfo.getUserInfo().getNickName());
            user.setUserType(SysConstant.USER_TYPE_STU);
            sysUserService.save(user);
        }

        String token = UserTokenManage.generateToken(user.getId(),
                user.getUsername(),
                user.getPassword());
        user.setPassword(null);
        Map<String, Object> r = new HashMap<>();
        r.put("userToken", token);
        r.put("userInfo", user);
        return R.success(r);
    }

    @PostMapping("test")
    public R loginByWeixin() throws WxErrorException {
        String accessToken = wxService.getAccessToken();
        Map<String,Object> data= new HashMap<>();
        Map<String,String> value = new HashMap<>();
        value.put("value", "发现您已经离开了座位，请尽快回到座位");
        data.put("thing1",value);

        value = new HashMap<>();
        value.put("value", "半个小时内未到位置，进行占座记录");
        data.put("thing3",value);
        WxSubscribeDto subscribeDto = WxSubscribeDto.builder()
                .access_token(accessToken)
                .touser("oxJ2X5EByLkcZzeO0_ulrbXFTNqA")
                .template_id("ggVUb3Cb76E77EVf4eGxCc-JYnwTP8ilkqLCuh2I7JE")
                .data(data).build();
        String s = JSON.toJSONString(subscribeDto);
        String responseContent = wxService.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send",
                s);

        return R.success();
    }
}